<template>
  <ProjectInfo :projectId="`${route.query.projectId}`" />

  <div class="preview-container">
    <!-- 主体内容区 -->
    <div class="main-content">
      <!-- 左侧文件列表 -->
      <div class="file-list">
        <el-card :body-style="{ padding: '0' }" class="file-list-card">
          <div class="search-box">
            <el-input v-model="searchKeyword" clearable placeholder="搜索文件" />
          </div>
          <el-scrollbar height="calc(100vh - 120px)">
            <el-menu :default-active="activeFile" @select="handleFileSelect">
              <el-menu-item v-for="file in filteredFileList" :key="file.id" :index="file.id">
                <span>{{ file.name }}</span>
              </el-menu-item>
            </el-menu>
          </el-scrollbar>
        </el-card>
      </div>

      <!-- 右侧PDF预览区域 -->
      <div v-loading="loading" class="pdf-wrapper">
        <iframe
          v-if="pdfUrl"
          :src="pdfUrl"
          height="100%"
          type="application/pdf"
          width="100%"
        ></iframe>
        <div v-else class="empty-state">
          <el-empty description="请选择要预览的文件" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import { ProjectApi } from '@/api/dk/project'
import { ElMessage } from 'element-plus'
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'

const route = useRoute()
const projectId = ref(Number(route.query.projectId) || 0)
const projectNo = ref(Number(route.query.projectNo) || 0)
const operationType = ref(Number(route.query.operationType) || 1)
const pdfUrl = ref('')
const loading = ref(false)
const activeFile = ref(operationType.value)
const searchKeyword = ref('')

defineOptions({ name: 'PreviewFile' })

// 初始化数据
const initData = async () => {
  if (operationType.value) {
    activeFile.value = operationType.value
    await handleRefresh()
  }
}

// 刷新预览
const handleRefresh = async () => {
  if (!activeFile.value || !projectId.value) return
  console.log('activeFile', activeFile.value)

  try {
    loading.value = true
    let data: Blob | null = null
    if (activeFile.value === 1) {
      data = await ProjectApi.previewProjectFieldSurvey(projectId.value)
    }
    if (activeFile.value === 2) {
      data = await ProjectApi.previewJobSurvey(projectId.value)
    }
    if (activeFile.value === 3) {
      data = await ProjectApi.previewPlanAudit(projectId.value)
    }
    if (activeFile.value === 4) {
      data = await ProjectApi.receiveInfoReview(projectId.value)
    }
    if (activeFile.value === 5) {
      data = await ProjectApi.reviewCalibration(projectId.value)
    }
    if (activeFile.value === 6) {
      data = await ProjectApi.previewConsumable(projectId.value)
    }

    if (activeFile.value === 7) {
      data = await ProjectApi.previewUnknownAnalysisRecord(projectId.value)
    }
    if (activeFile.value === 8) {
      data = await ProjectApi.previewtHarmfulFactorsRecord(projectId.value)
    }

    if (activeFile.value === 9) {
      data = await ProjectApi.previewtSampleHandoverRecord(projectId.value, 2)
    }

    if (activeFile.value === 10 ) {
      data = await ProjectApi.previewtSampleHandoverRecord(projectId.value, 1)
    }
    if ( activeFile.value === 91) {
      data = await ProjectApi.previewtSampleHandoverRecord(projectId.value, 3)
    }
    if (activeFile.value === 11) {
      data = await ProjectApi.previewtBeforeSample(projectId.value)
    }

    if (activeFile.value === 12) {
      data = await ProjectApi.previewtAfterSample(projectId.value)
    }

    if (activeFile.value === 13) {
      data = await ProjectApi.previewtEyhg(projectId.value)
    }

    if (activeFile.value === 14) {
      data = await ProjectApi.previewExperimentalResults(projectId.value)
    }

    if (activeFile.value === 15) {
      data = await ProjectApi.previewRgularlyTestTemplates(projectId.value)
    }
    if (activeFile.value === 16) {
      data = await ProjectApi.resultCalculation(projectId.value)
    }
    if (activeFile.value === 41) {
      data = await ProjectApi.reviewRegistrationCalibrationRecord(projectId.value)
    }

    if (data) {
      const newBlob = new Blob([data], { type: 'application/pdf' })
      pdfUrl.value = URL.createObjectURL(newBlob)
      ElMessage.success('预览已更新')
    }
  } catch (error) {
    // console.error('预览更新失败:', error)
    // ElMessage.error('预览更新失败，请重试')
  } finally {
    loading.value = false
  }
}

// 选择文件
const handleFileSelect = async (fileId: number) => {
  activeFile.value = fileId
  await handleRefresh()
}

// 模拟文件列表数据，实际项目中应该从API获取
const sortedFileList = ref([
  { id: 1, name: '现场调查表' },
  { id: 7, name: '定性采样表' },
  { id: 91, name: '定性样品流转表' },
  { id: 2, name: '采样方案表' },
  { id: 3, name: '方案审核表' },
  { id: 41, name: '设备出入登记及校准' },
  // { id: 4, name: '设备领用' },
  // { id: 5, name: '设备校验' },
  { id: 6, name: '耗材申请领用表' },

  { id: 8, name: '采样记录表' },
  { id: 11, name: '滤膜采样前' },
  { id: 10, name: '样品流转' },
  { id: 12, name: '滤膜采样后' },
  { id: 13, name: '二氧化硅含量' },
  { id: 16, name: '接触浓度计算' },
  { id: 14, name: '实验报告' },
  { id: 15, name: '检测报告' }
])

const fileList = computed(() => {
  return sortedFileList.value.map((item, index) => ({
    ...item,
    // 索引+1 作为序列号，补0保持两位（如1→"01"，10→"10"）
    name: `${(index + 1).toString().padStart(2, '0')}${item.name}`
  }));
});

// 过滤文件列表
const filteredFileList = computed(() => {
  if (!searchKeyword.value) return fileList.value
  return fileList.value.filter((file) =>
    file.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 初始化
initData()
</script>

<style scoped>
.preview-container {
  height: 100%;
  background-color: var(--el-bg-color);
  padding: 0px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
  padding: 0 0px;
  background-color: white;
}

.main-content {
  display: flex;
  height: calc(100vh - 60px);
}

.file-list {
  width: 180px;
  flex-shrink: 0;
  background: #f7f8fa;
  border-right: 1px solid #ebeef5;
}

.file-list-card {
  height: 100%;
  border-radius: 0;
  box-shadow: none;
  background: transparent;
  border: none;
}

.search-box {
  padding: 0px;
  border-bottom: 1px solid var(--el-border-color-light);
  background: #f7f8fa;
}

:deep(.el-scrollbar__view) {
  padding: 7px 0;
}

:deep(.el-menu) {
  border-right: none;
  background: transparent;
  display: flex;
  flex-direction: column;
}

:deep(.el-menu-item) {
  border: 1px solid #e4e7ed;
  border-radius: 0 !important;

  height: 45px;
  line-height: 38px;
  font-size: 14px;
  padding-left: 10px !important;
  transition:
    background 0.2s,
    border-color 0.2s;
  box-shadow: none !important;
}

:deep(.el-menu-item.is-active) {
  color: #409eff;
  background: #eaf3ff !important;
  border-color: #409eff;
}

:deep(.el-menu-item:hover) {
  background: #f0f7ff !important;
  color: #409eff;
  border-color: #b3d8fd;
}

.pdf-wrapper {
  flex: 1;
  background: white;
  overflow: hidden;
  position: relative;
}

iframe {
  width: 100%;
  height: 100%;
  border: none;
}
</style>
